from rest_framework.views import APIView
from apps.coffee.models import templates
from datetime import datetime
from utils.response import ApiResponse
from apps.coffee.models import fields
import json,time

class TemplatesView(APIView):
    """
    咖啡模板管理
    """
    def get(self, request):
        """
        获取所有咖啡模板信息

        参数:
            request (Request): DRF请求对象

        返回:
            ApiResponse: 包含咖啡模板信息的响应

        异常:
            500: 获取数据失败
        """
        try:
            data = templates.objects.all().order_by('-id').values(
                'id', 'name', 'description', 'fields','create_time', 'status'
            )
            for item in data:
                try:
                    # 解析 fields 字段
                    if isinstance(item['fields'], str):
                        field_ids = json.loads(item['fields'])
                    else:
                        field_ids = item['fields'] = []
                    if item['create_time']:
                        try:
                            item['create_time'] = datetime.fromtimestamp(item['create_time']).strftime('%Y-%m-%d %H:%M:%S')
                        except (TypeError,OSError):
                            item['create_time'] = None
                    # 如果存在字段 ID，则查询完整字段信息
                    if field_ids:
                        full_fields = list(fields.objects.filter(id__in=field_ids).values())
                        for field in full_fields:
                            field['value'] = json.loads(field['value']) if field['value'] else []
                        item['full_fields'] = full_fields
                    else:
                        item['full_fields'] = []
                except (json.JSONDecodeError, TypeError):
                    item['fields'] = []
                    item['full_fields'] = []
            return ApiResponse(data=list(data))
        except Exception as e:
            return ApiResponse(code=500, message=str(e))

    def post(self, request):
        """
        创建新的咖啡模板

        参数:
            request (Request): DRF请求对象，包含新的咖啡模板数据

        返回:
            ApiResponse: 创建结果响应

        异常:
            400: 验证失败
            500: 创建失败
        """
        try:
            validated_data = self._validate_and_filter_templates(request.data)
            templates.objects.create(**validated_data)
            return ApiResponse(message='创建成功')
        except Exception as e:
            return ApiResponse(code=500, message=str(e))
        
    def put(self, request, pk):
        """更新咖啡模板

        参数:
            request (Request): DRF请求对象，包含新的咖啡模板数据
            kwargs (dict): URL参数，包含模板ID

        返回:
            ApiResponse: 更新结果响应

        异常:
            400: 验证失败
            500: 更新失败
        """
        try:
            template_obj = templates.objects.get(pk=pk)
            data = request.data
            validate_data = self._validate_and_filter_templates(data, True)
           
            for key, value in validate_data.items():
                setattr(template_obj, key, value)
            template_obj.save()
            return ApiResponse(message='更新成功')
        except Exception as e:
            return ApiResponse(code=500, message=str(e))

    def delete(self, request,pk):
        """
        删除模板
        """
        try:
            template_obj = templates.objects.filter(id=pk).first()
            if not template_obj:
                return ApiResponse(code=400, message='模板不存在')
            template_obj.delete()
            return ApiResponse(message='删除成功')
        except Exception as e:
            return ApiResponse(code=500, message=str(e))

    #数据校验
    def _validate_and_filter_templates(self, data, is_update=False):
        fields = ['id', 'name', 'description', 'fields','create_time','status']
        result = {}
        for field in fields:
            value = data.get(field)
            if not is_update or (field in data):  # 更新时仅当字段存在才更新
                result[field] = value
                if field == 'fields':
                    result[field] = json.dumps(value)
                if not is_update:
                    result['create_time'] = int(time.time())
                    result.pop('id', None)
        return result